#include "StdAfx.h"

#if defined(CRY_ENABLE_RC_HELPER)

#include "SettingsManagerHelpers.h"

#include <Windows.h>


bool SettingsManagerHelpers::Utf16ContainsAsciiOnly(const wchar_t* wstr)
{
	while (*wstr)
	{
		if (*wstr > 127 || *wstr < 0)
		{
			return false;
		}
		++wstr;
	}
	return true;
}


void SettingsManagerHelpers::ConvertUtf16ToUtf8(const wchar_t* src, CCharBuffer dst)
{
	if (dst.getSizeInElements() <= 0)
	{
		return;
	}

	if (src[0] == 0)
	{
		dst[0] = 0;
	}
	else
	{
		const size_t len = wcslen(src);
		const int byteCount = WideCharToMultiByte(
			CP_UTF8, 
			0, 
			src,
			len,
			dst.getPtr(), // output buffer
			dst.getSizeInBytes() - 1,  // size of the output buffer in bytes
			NULL,    
			NULL);
		if (byteCount <= 0 || byteCount >= (int)dst.getSizeInBytes())
		{
			dst[0] = 0;
		}
		else
		{
			dst[byteCount] = 0;
		}
	}
}


void SettingsManagerHelpers::ConvertUtf8ToUtf16(const char* src, CWCharBuffer dst)
{
	if (dst.getSizeInElements() <= 0)
	{
		return;
	}

	if (src[0] == 0)
	{
		dst[0] = 0;
	}
	else
	{
		const size_t len = strlen(src);
		const int charCount = MultiByteToWideChar(
			CP_UTF8, 
			0, 
			src,
			len,
			dst.getPtr(), // output buffer
			dst.getSizeInElements() - 1);  // size of the output buffer in characters
		if (charCount <= 0 || charCount >= (int)dst.getSizeInElements())
		{
			dst[0] = 0;
		}
		else
		{
			dst[charCount] = 0;
		}
	}
}


void SettingsManagerHelpers::GetAsciiFilename(const wchar_t* wfilename, CCharBuffer buffer)
{
	if (buffer.getSizeInElements() <= 0)
	{
		return;
	}

	if (wfilename[0] == 0)
	{
		buffer[0] = 0;
		return;
	}

	if (Utf16ContainsAsciiOnly(wfilename))
	{
		ConvertUtf16ToUtf8(wfilename, buffer);
		return;
	}

	// The path is non-ASCII unicode, so let's resort to short filenames (they are always ASCII-only, I hope)
	wchar_t shortW[MAX_PATH];
	const int bufferCharCount = sizeof(shortW) / sizeof(shortW[0]);
	const int charCount = GetShortPathNameW(wfilename, shortW, bufferCharCount);
	if (charCount <= 0 || charCount >= bufferCharCount)
	{
		buffer[0] = 0;
		return;
	}

	shortW[charCount] = 0;
	if (!Utf16ContainsAsciiOnly(shortW))
	{
		buffer[0] = 0;
		return;
	}

	ConvertUtf16ToUtf8(shortW, buffer);
}

#endif // defined(CRY_ENABLE_RC_HELPER)

// eof
